﻿using AntdUI;
using Lima.ResumeSys.DAL;
using Lima.ResumeSys.Models;
using Lima.ResumeSys.Util;
using Org.BouncyCastle.Utilities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static Lima.ResumeSys.Models.PerFile;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace Lima.ResumeSys.PersonControl
{
    public partial class EditFIle : UserControl
    {
        private AntdUI.Window window;
        private string _PerNo = "";
        private bool result = false;
        List<PerFile> fileList;
        private string _PerFileId = "";
        PerFileDAL perFileDal = new PerFileDAL();
        SysUtil util = new SysUtil();
        public EditFIle(AntdUI.Window _window,string perNo)
        {
            window = _window;
            _PerNo = perNo;
            InitializeComponent();
            BindFile();
            InitPerFileColumns();
            InitPerFileData();
        }

        #region 附件信息
   

        private void InitPerFileData()
        {

            fileList = new List<PerFile>();

            QueryPerFileModel query = new QueryPerFileModel();
            query.PerNo = _PerNo;
            var list = perFileDal.GetList(query);
            foreach (var item in list)
            {
                fileList.Add(new PerFile
                {
                    FileName = item.FileName,
                    FileSize = item.FileSize,
                    Creator = item.Creator,
                    CreateTimeText = item.CreateTime.ToString("d"),
                    CellLinks = new CellLink[] {
                    new CellButton(item.PerFileId,"下载",TTypeMini.Primary),
                    new CellButton(item.PerFileId,"删除",TTypeMini.Error)},
                });
            }
            tableFile.DataSource = fileList;
        }
        private void InitPerFileColumns()
        {
            tableFile.Columns = new ColumnCollection() {
                new Column("","序号"){
                    Width = "50",
                    Render = (value,record,rowindex)=>{return (rowindex+1); },
                    Fixed = true,//冻结列
                },
                new Column("FileName", "文件名称", ColumnAlign.Left),
                new Column("FileSize", "文件大小", ColumnAlign.Left),
                new Column("Creator", "创建人", ColumnAlign.Left),
                new Column("CreateTimeText", "创建时间",ColumnAlign.Left),
                new Column("CellLinks", "操作", ColumnAlign.Center),
            };
        }
        private void tableFile_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            switch (e.Btn.Text)
            {   //暂不支持进入整行编辑，只支持指定单元格编辑，推荐使用弹窗或抽屉编辑整行数据
                case "下载":

                    PerFile entity = perFileDal.GetModel(e.Btn.Id);
                    byte[] fileData = Convert.FromBase64String(entity.FileContent);
                    string directoryPath = util.CreateFilePerNo(_PerNo);
                    string filePath = Path.Combine(directoryPath, entity.FileName);
                    File.WriteAllBytes(filePath, fileData);
                    AntdUI.Message.success(window, $"文件已保存到：{Path.GetFullPath(entity.FileName)}", autoClose: 3);
                    break;
                case "删除":
                    var result = Modal.open(window, "删除警告！", "确认要删除选择的数据吗？", TType.Warn);
                    if (result == DialogResult.OK)
                    {
                        if (perFileDal.Del(e.Btn.Id))
                        {
                            AntdUI.Message.success(window, "删除成功！", autoClose: 3);
                        }
                        else
                        {
                            AntdUI.Message.error(window, "删除失败！", autoClose: 3);
                        }
                    }
                    break;
            }
            InitPerFileData();
        }
        private void BindFile()
        {
            //1.7.14开始,uploadDragger自带点击打开文件选择框
            upFile.DragChanged += upFile_DragChanged;
            upFile.Multiselect = false;//允许多选文件
            upFile.Filter = "All Files (*.*)|*.*";//文件筛选
            upFile.HandDragFolder = false;//是否支持拖拽，默认为true
        }


        private void upFile_DragChanged(object sender, StringsEventArgs e)
        {
            result = false;
            string[] filePaths = e.Value;
            PerFile entity;
            FileInfo fileInfo;
            string fileSizeInBytes;
            try
            {
                string path = filePaths[0];
                fileInfo = new FileInfo(path);

                // 获取文件大小（字节）
                fileSizeInBytes = Math.Round(fileInfo.Length / (1024.0 * 1024.0), 2).ToString() + "MB";
                entity = new PerFile();
                entity.PerFileId = Guid.NewGuid().ToString();
                entity.PerNo = _PerNo;
                entity.FileName = Path.GetFileName(path);
                entity.FileUrl = path;
                entity.FileSize = fileSizeInBytes;
                entity.Creator = CurrentUser.UserName;
                result = perFileDal.Add(entity);

                if (result)
                {
                    AntdUI.Message.success(window, "上传成功！", autoClose: 3);
                }
                else
                {
                    AntdUI.Message.error(window, "上传失败！", autoClose: 3);
                }
                InitPerFileData();
            }
            catch (Exception)
            {
                AntdUI.Message.error(window, "上传失败！", autoClose: 3);
            }
        }



        #endregion

    }
}
